#!/usr/bin/python
# -*- coding: utf-8 -*-

from django import forms
from django.forms.util import ErrorList
from django.contrib.auth import authenticate
from django.contrib.auth.models import User


class BootstrapErrorList(ErrorList):
    def __unicode__(self):
        return self.as_alert()

    def as_alert(self):
        if not self:
            return u''
        error_div = u'''
<div class="alert alert-error">
    <button type="button" class="close" data-dismiss="alert">×</button>
    %s
</div>'''
        return ''.join([error_div % e for e in self])


class SignupForm(forms.Form):
    name = forms.CharField(max_length=30, label=u'Imię')
    last_name = forms.CharField(max_length=30, label='Nazwisko')
    login = forms.EmailField(max_length=75, label='Mail')
    password = forms.CharField(widget=forms.PasswordInput, label=u'Hasło',
                               min_length=5, max_length=128)

    # def __init__(self, auto_id='login_%s', error_class=BootstrapErrorList,
                 # *args, **kwargs):
        # super(SignupForm, self).__init__(auto_id='signup_%s',
                                        # error_class=BootstrapErrorList,
                                        # *args, **kwargs)

    def clean_login(self):
        cc_login = self.cleaned_data['login']
        if User.objects.filter(username=cc_login):
            raise forms.ValidationError(u'Użytkownik o podanym mailu istnieje')
        return cc_login


class LoginForm(forms.Form):
    login = forms.EmailField(max_length=75, label='Mail')
    password = forms.CharField(widget=forms.PasswordInput, label=u'Hasło',
                               min_length=5, max_length=128)

    # def __init__(self, auto_id='login_%s', error_class=BootstrapErrorList,
                 # *args, **kwargs):
        # super(LoginForm, self).__init__(auto_id='login_%s',
                                        # error_class=BootstrapErrorList,
                                        # *args, **kwargs)

    def clean(self):
        cleaned_data = super(LoginForm, self).clean()
        cc_login = cleaned_data.get('login')
        cc_password = cleaned_data.get('password')
        user = authenticate(username=cc_login, password=cc_password)
        if not user:
            raise forms.ValidationError(u'Mail i hasło nie pasują do siebie')
        elif not user.is_active:
            raise forms.ValidationError(u'Użytkownik nie jest aktywny')
        return cleaned_data
